<template>
  <div class="admin-main-page">
    <!-- 顶部导航栏 -->
    <el-header class="admin-header">
      <div class="header-content">
        <div class="logo">
          <el-icon :size="28"><House /></el-icon>
          <h1>智能家居控制中心 - 管理员</h1>
        </div>
        <div class="header-stats">
          <el-tag type="success" size="large">
            <el-icon><Switch /></el-icon>
            {{ activeDevicesCount }} 设备运行中
          </el-tag>
          <el-dropdown @command="handleUserCommand">
            <span class="user-info">
              <el-icon><User /></el-icon>
              {{ user?.nickname || user?.username }}
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                <el-dropdown-item command="settings">系统设置</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-container>
      <!-- 侧边栏 -->
      <el-aside class="admin-sidebar" width="250px">
        <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="services">
            <el-icon><Tools /></el-icon>
            <span>服务申请</span>
          </el-menu-item>
          <el-menu-item index="statistics">
            <el-icon><DataAnalysis /></el-icon>
            <span>系统统计</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-main class="admin-main">
        <!-- 用户管理 -->
        <AdminPanel v-if="activeMenu === 'users'" />
        
        <!-- 服务申请 -->
        <AdminServiceRequestPanel v-else-if="activeMenu === 'services'" />
        
        <!-- 系统统计 -->
        <div v-else-if="activeMenu === 'statistics'" class="statistics">
            <div class="statistics-content">
            <h2>系统统计</h2>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-value">{{ userStats.totalUsers }}</div>
                    <div class="stat-label">总用户数</div>
                    <div class="stat-detail">
                      <span class="detail-item">活跃: {{ userStats.activeUsers }}</span>
                      <span class="detail-item">管理员: {{ userStats.adminUsers }}</span>
                      <span class="detail-item">维修师傅: {{ userStats.maintenanceUsers }}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-value">{{ deviceStats.totalDevices }}</div>
                    <div class="stat-label">总设备数</div>
                    <div class="stat-detail">
                      <span class="detail-item">在线: {{ deviceStats.onlineDevices }}</span>
                      <span class="detail-item">离线: {{ deviceStats.offlineDevices }}</span>
                      <span class="detail-item">在线率: {{ Math.round(deviceStats.onlineRate * 100) }}%</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-value">{{ serviceStats.total }}</div>
                    <div class="stat-label">服务申请</div>
                    <div class="stat-detail">
                      <span class="detail-item">待处理: {{ serviceStats.pending }}</span>
                      <span class="detail-item">处理中: {{ serviceStats.inProgress }}</span>
                      <span class="detail-item">已完成: {{ serviceStats.completed }}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-value">{{ sceneStats.totalScenes }}</div>
                    <div class="stat-label">场景总数</div>
                    <div class="stat-detail">
                      <span class="detail-item">激活: {{ sceneStats.activeScenes }}</span>
                      <span class="detail-item">未激活: {{ sceneStats.inactiveScenes }}</span>
                      <span class="detail-item">紧急: {{ serviceStats.urgent + serviceStats.veryUrgent }}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            </div>
          </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { 
  House, Switch, User, Tools, DataAnalysis, ArrowDown 
} from '@element-plus/icons-vue'
import { useAuthStore } from '../store/authStore.js'
import { useDeviceStore } from '../store/deviceStore.js'
import { adminAPI } from '../services/api.js'
import AdminPanel from './AdminPanel.vue'
import AdminServiceRequestPanel from './AdminServiceRequestPanel.vue'

export default {
  name: 'AdminMainPage',
  components: {
    House,
    Switch,
    User,
    Tools,
    DataAnalysis,
    ArrowDown,
    AdminPanel,
    AdminServiceRequestPanel
  },
  setup() {
    const authStore = useAuthStore()
    const deviceStore = useDeviceStore()
    const activeMenu = ref('users')
    
    const activeDevicesCount = computed(() => deviceStore.activeDevicesCount.value)
    
    // 统计数据
    const userStats = reactive({
      totalUsers: 0,
      activeUsers: 0,
      inactiveUsers: 0,
      adminUsers: 0,
      maintenanceUsers: 0,
      normalUsers: 0
    })
    
    const deviceStats = reactive({
      totalDevices: 0,
      onlineDevices: 0,
      offlineDevices: 0,
      onlineRate: 0
    })
    
    const serviceStats = reactive({
      total: 0,
      pending: 0,
      inProgress: 0,
      completed: 0,
      cancelled: 0,
      urgent: 0,
      veryUrgent: 0
    })
    
    const sceneStats = reactive({
      totalScenes: 0,
      activeScenes: 0,
      inactiveScenes: 0
    })
    
    // 加载管理员统计数据
    const loadAdminStats = async () => {
      try {
        console.log('开始加载管理员统计数据...')
        const stats = await adminAPI.getDashboardStats()
        console.log('管理员统计数据:', stats)
        
        // 更新用户统计
        if (stats.userStats) {
          Object.assign(userStats, stats.userStats)
        }
        
        // 更新设备统计
        if (stats.deviceStats) {
          Object.assign(deviceStats, stats.deviceStats)
        }
        
        // 更新服务申请统计
        if (stats.serviceStats) {
          Object.assign(serviceStats, stats.serviceStats)
        }
        
        // 更新场景统计
        if (stats.sceneStats) {
          Object.assign(sceneStats, stats.sceneStats)
        }
        
        console.log('管理员统计数据加载完成')
      } catch (error) {
        console.error('加载管理员统计数据失败:', error)
        // 设置默认值
        userStats.totalUsers = 0
        deviceStats.totalDevices = 0
        serviceStats.total = 0
        sceneStats.totalScenes = 0
      }
    }
    
    const handleMenuSelect = (index) => {
      activeMenu.value = index
    }
    
    const handleLogout = () => {
      authStore.logout()
    }
    
    const handleUserCommand = (command) => {
      switch (command) {
        case 'profile':
          activeMenu.value = 'profile'
          break
        case 'settings':
          activeMenu.value = 'settings'
          break
        case 'logout':
          handleLogout()
          break
      }
    }
    
    // 组件挂载时加载数据
    onMounted(async () => {
      try {
        if (authStore.checkAuth()) {
          // 先加载设备数据，再加载统计数据
          await deviceStore.loadUserDevices()
          await loadAdminStats()
        }
      } catch (error) {
        console.error('组件挂载时出错:', error)
      }
    })
    
    // 组件卸载时清理数据
    onUnmounted(() => {
      try {
        // 清理统计数据
        userStats.totalUsers = 0
        userStats.activeUsers = 0
        userStats.inactiveUsers = 0
        userStats.adminUsers = 0
        userStats.maintenanceUsers = 0
        userStats.normalUsers = 0
        
        deviceStats.totalDevices = 0
        deviceStats.onlineDevices = 0
        deviceStats.offlineDevices = 0
        deviceStats.onlineRate = 0
        
        serviceStats.total = 0
        serviceStats.pending = 0
        serviceStats.inProgress = 0
        serviceStats.completed = 0
        serviceStats.cancelled = 0
        serviceStats.urgent = 0
        serviceStats.veryUrgent = 0
        
        sceneStats.totalScenes = 0
        sceneStats.activeScenes = 0
        sceneStats.inactiveScenes = 0
      } catch (error) {
        console.warn('清理数据时出错:', error)
      }
    })
    
    return {
      activeMenu,
      activeDevicesCount,
      userStats,
      deviceStats,
      serviceStats,
      sceneStats,
      loadAdminStats,
      handleMenuSelect,
      handleLogout,
      handleUserCommand,
      isLoggedIn: authStore.isLoggedIn,
      user: authStore.user
    }
  }
}
</script>

<style scoped>
.admin-main-page {
  height: 100vh;
  background: #f5f7fa;
}

.admin-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 30px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.header-stats {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: white;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.admin-sidebar {
  background: #fff;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.sidebar-menu {
  border-right: none;
  height: 100%;
}

.sidebar-menu .el-menu-item {
  height: 60px;
  line-height: 60px;
  font-size: 16px;
  font-weight: 500;
}

.sidebar-menu .el-menu-item:hover {
  background-color: #f0f8ff;
  color: #409eff;
}

.sidebar-menu .el-menu-item.is-active {
  background-color: #e6f3ff;
  color: #409eff;
  border-right: 3px solid #409eff;
}

.admin-main {
  padding: 0;
  background: #f5f7fa;
  overflow-y: auto;
}

.dashboard,
.users,
.devices,
.services,
.statistics,
.settings {
  padding: 20px;
}

.statistics-content h2 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.stat-card {
  text-align: center;
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.stat-content {
  padding: 20px;
}

.stat-value {
  font-size: 32px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  font-weight: 500;
}

.stat-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: 100%;
}

.detail-item {
  font-size: 12px;
  color: #909399;
  padding: 2px 8px;
  background: #f5f7fa;
  border-radius: 4px;
  margin: 1px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-sidebar {
    width: 200px !important;
  }
  
  .header-content {
    padding: 0 15px;
  }
  
  .logo h1 {
    font-size: 20px;
  }
  
  .header-stats {
    display: none;
  }
}

@media (max-width: 480px) {
  .admin-sidebar {
    width: 60px !important;
  }
  
  .sidebar-menu .el-menu-item span {
    display: none;
  }
  
  .logo h1 {
    display: none;
  }
}
</style>
